package mapReduce.demo01_wordCount;

import mapReduce.util.JobSubmit;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WordCountApp {

    public static class WCMapper extends Mapper<LongWritable, Text,Text, IntWritable>{

        Text outKey = new Text();
        IntWritable outValue = new IntWritable(1);

        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] words = line.split(" ");
            for (String word : words) {
                outKey.set(word);
                context.write(outKey,outValue);
            }
        }
    }

    public static class WCReducer extends Reducer<Text,IntWritable,Text, NullWritable>{

        Text outKey = new Text();

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, NullWritable>.Context context) throws IOException, InterruptedException {

            int sum = 0;
            for (IntWritable value : values) {
                sum+=value.get();
            }

            outKey.set(key.toString()+"\t"+sum);

            context.write(outKey,NullWritable.get());

        }
    }


    public static void main(String[] args){

        Map<String,String> propMap = new HashMap<>();
        propMap.put("fs.defaultFS","file:///");

        JobSubmit.submitBaseJob(WordCountApp.class,args,0);
    }


}
